package com.blog.controller.admin;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import com.blog.controller.BackendController;
import com.blog.model.Category;
import com.blog.model.News;
import com.blog.model.User;
import com.blog.model.UserVo;
import com.blog.service.CategoryService;
import com.blog.service.NewsService;
import com.blog.service.UserService;
import com.blog.utils.CookieKit;
import com.blog.utils.JsonResult;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import sun.security.provider.MD5;

import javax.servlet.ServletContext;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/admin/news")
public class NewsController extends BackendController {

    Map<String, Object> result = new HashMap<String, Object>();

    @Resource
    protected NewsService newsService;

    @Resource
    protected CategoryService CategoryService;

    @Resource
    protected UserService userService;

    @Resource
    private ServletContext servletContext;

    @Resource
    private HttpServletRequest request;

    @Resource
    private HttpServletResponse response;


    String relativePath;
    String newFileName;

    /**
     * 读取资讯列表
     * */
    @GetMapping("")
    public ModelAndView index(News news,HttpServletRequest request){
        /*List<News> data = NewsService.findAll();
        request.setAttribute("data", data);
        return "admin/news/index";*/

        //获取分类
        List<Category> category = CategoryService.selectAll();
        request.setAttribute("category",category);

        //获取用户名
        List<User> user = userService.findAll();
        request.setAttribute("users",user);

        ModelAndView result = new ModelAndView("admin/news/index");

        List<News> newsList = newsService.findAll(news);
        Object pageInfo = new PageInfo<News>(newsList);


        result.addObject("pageInfo", new PageInfo<News>(newsList));
        result.addObject("queryParam", news);
        result.addObject("page", news.getPage());
        result.addObject("rows", news.getRows());
        return result;

    }
    /**
     * 添加内容控制器
     * */
    @RequestMapping("/add")
    public String add(HttpServletRequest request,Category category){
        //获取分类
        List<Category> data = CategoryService.selectAll();
        request.setAttribute("data",data);
        return "admin/news/add";
    }

    @RequestMapping("edit/{id}")
    public String edit(@PathVariable Integer id, HttpServletRequest request){
        News data = newsService.getNews(id);
        request.setAttribute("info", data);
        List<Category> category = CategoryService.selectAll();
        request.setAttribute("category",category);
        return "admin/news/edit";
    }

    @RequestMapping(value = "/doAdd",method = RequestMethod.POST)
    public String doAdd(@Param("cateid") int cateid, @Param("order") byte order, @Param("status") byte status, @RequestParam("thumb") MultipartFile file, RedirectAttributes redirectAttributes, HttpServletRequest request) throws IOException{
        //获取标题
        String title = request.getParameter("title");

        // 获取上传的文件名
        String fileName = file.getOriginalFilename();
        String thumb = "";
        if(fileName.length() > 0){
            // 获取文件的后缀名
            String extName = fileName .substring(fileName.lastIndexOf("."));
            // 文件保存的相对位置，相对于upload
            relativePath = File.separator + "images" + File.separator;

            // 生成的文件名
            Long dateTimeLong = Calendar.getInstance().getTimeInMillis();
            newFileName = generateFileName(dateTimeLong, extName);
            // 文件保存的完整目录
            String absolutePath = servletContext.getRealPath("upload") + relativePath;

            File temp = new File(absolutePath);
            if (!temp.exists()) {
                temp.mkdirs();  // 如果目录不存在则创建
            }


            BufferedOutputStream stream = null;
            stream = new BufferedOutputStream(new FileOutputStream(absolutePath + newFileName));
            if(stream != null){
                stream.write(file.getBytes());
                stream.close();
            }
            //返回给编辑器的文件位置
            thumb = File.separator + "upload" + relativePath + newFileName;
        }



        //获取关键词
        String keywords = request.getParameter("keywords");
        //获取摘要
        String description = request.getParameter("description");
        //获取内容
        String content = request.getParameter("content");
        relativePath = File.separator + "images" + File.separator;
        UserVo sessionObject = getLoginUser();

        byte num = 1;
        News news = new News();
        news.setCateid(cateid);
        news.setTitle(title);
        news.setThumb(thumb);
        news.setKeywords(keywords);
        news.setDescription(description);
        news.setContent(content);
        news.setOrder(order);
        news.setStatus(status);
        news.setUserid(sessionObject.getId());
        news.setReadnum(1);
        news.setUpdatetime(new Date());
        news.setCreatetime(new Date());
        newsService.save(news);

        return "redirect:/admin/news";
    }
    //@RequestParam("thumb") MultipartFile file

    @RequestMapping(value = "doEdit", method = RequestMethod.POST)
    public String doEdit(@Param("id") int id,@Param("cateid") int cateid, @Param("order") byte order, @Param("status") byte status, @RequestParam("thumb") MultipartFile file, RedirectAttributes redirectAttributes, HttpServletRequest request) throws IOException{

        //获取标题
        String title = request.getParameter("title");


        // 获取上传的文件名
        String thumb = "";
        String fileName = file.getOriginalFilename();
        if(fileName.length() > 0){
            // 获取文件的后缀名
            String extName = fileName .substring(fileName.lastIndexOf("."));
            // 文件保存的相对位置，相对于upload
            relativePath = File.separator + "images" + File.separator;

            // 生成的文件名
            Long dateTimeLong = Calendar.getInstance().getTimeInMillis();
            newFileName = generateFileName(dateTimeLong, extName);
            // 文件保存的完整目录
            String absolutePath = servletContext.getRealPath("upload") + relativePath;

            File temp = new File(absolutePath);
            if (!temp.exists()) {
                temp.mkdirs();  // 如果目录不存在则创建
            }


            BufferedOutputStream stream = null;
            stream = new BufferedOutputStream(new FileOutputStream(absolutePath + newFileName));
            if(stream != null){
                stream.write(file.getBytes());
                stream.close();
            }
            //返回给编辑器的文件位置
            thumb = File.separator + "upload" + relativePath + newFileName;
        }else{
            thumb = request.getParameter("thumbImg");
        }



        //获取关键词
        String keywords = request.getParameter("keywords");
        //获取摘要
        String description = request.getParameter("description");
        //获取内容
        String content = request.getParameter("content");
        relativePath = File.separator + "images" + File.separator;

        News news = new News();
        news.setId(id);
        news.setCateid(cateid);
        news.setTitle(title);
        news.setThumb(thumb);
        news.setKeywords(keywords);
        news.setDescription(description);
        news.setContent(content);
        news.setOrder(order);
        news.setStatus(status);
        news.setUserid(1);
        news.setUpdatetime(new Date());
        newsService.editNews(news);

        return "redirect:/admin/news";
    }

    @RequestMapping("/delete")
    @ResponseBody
    public JsonResult delete(@Param("id") Integer id){
        try{
            newsService.delete(id);
            return JsonResult.ok();
        }catch (Exception e){
            return JsonResult.fail(e.getMessage());
        }

    }


    /**
     * 生成规范的文件名
     */
    private String generateFileName(Long datetime, String extName) {
        return datetime + extName;
    }


}
